<template>
  <div class="page-scan">
    <Eheader @back="clickIndexLeft"><span>扫描二维码/条形码</span></Eheader>
    <!-- 扫码区域 -->
    <video ref="video" id="video" class="scan-video" autoplay></video>
    <!-- 提示语 -->
    <div v-show="tipShow" class="scan-tip">{{ tipMsg }}</div>
  </div>
</template>
 
<script>
import Eheader from "../../components/e-header.vue";
import { BrowserMultiFormatReader } from "@zxing/library";
import { Icon } from "vant";
export default {
  name: "scan",
  components: { "van-icon": Icon, Eheader },
  props: {
    type: String,
  },
  data() {
    return {
      loadingShow: false,
      codeReader: null,
      scanText: "",
      tipMsg: "正在尝试识别....",
      tipShow: false,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.codeReader = new BrowserMultiFormatReader();
      this.openScan();
    });
  },
  beforeDestroy() {
    if (this.codeReader) {
      this.codeReader.reset();
      this.codeReader.stopContinuousDecode();
      this.codeReader = null;
    }
  },
  watch: {
    $route(to, from) {
      if (to.path.indexOf("/scan/") > -1) {
        this.codeReader = new BrowserMultiFormatReader();
        this.openScanTwo();
      }
    },
  },
  methods: {
    async openScan() {
      this.codeReader
        .getVideoInputDevices()
        .then((videoInputDevices) => {
          this.tipShow = true;
          this.tipMsg = "正在调用摄像头...";
          console.log("videoInputDevices", videoInputDevices);
          // 默认获取第一个摄像头设备id
          let firstDeviceId = videoInputDevices[0].deviceId;
          // 获取第一个摄像头设备的名称
          const videoInputDeviceslablestr = JSON.stringify(
            videoInputDevices[0].label
          );
          if (videoInputDevices.length > 1) {
            // 判断是否后置摄像头
            if (videoInputDeviceslablestr.indexOf("back") > -1) {
              firstDeviceId = videoInputDevices[0].deviceId;
            } else {
              firstDeviceId = videoInputDevices[1].deviceId;
            }
          }
          this.decodeFromInputVideoFunc(firstDeviceId);
        })
        .catch((err) => {
          this.tipShow = false;
          console.error(err);
        });
    },
    async openScanTwo() {
      this.codeReader = await new BrowserMultiFormatReader();
      this.codeReader
        .getVideoInputDevices()
        .then((videoInputDevices) => {
          this.tipShow = true;
          this.tipMsg = "正在调用摄像头...";
          console.log("videoInputDevices", videoInputDevices);
          // 默认获取第一个摄像头设备id
          let firstDeviceId = videoInputDevices[0].deviceId;
          // 获取第一个摄像头设备的名称
          const videoInputDeviceslablestr = JSON.stringify(
            videoInputDevices[0].label
          );
          if (videoInputDevices.length > 1) {
            // 判断是否后置摄像头
            if (videoInputDeviceslablestr.indexOf("back") > -1) {
              firstDeviceId = videoInputDevices[0].deviceId;
            } else {
              firstDeviceId = videoInputDevices[1].deviceId;
            }
          }
          this.decodeFromInputVideoFunc(firstDeviceId);
        })
        .catch((err) => {
          this.tipShow = false;
          console.error(err);
        });
    },
    decodeFromInputVideoFunc(firstDeviceId) {
      this.codeReader.reset(); // 重置
      this.scanText = "";
      this.codeReader.decodeFromInputVideoDeviceContinuously(
        firstDeviceId,
        "video",
        (result, err) => {
          this.tipMsg = "正在尝试识别...";
          this.scanText = "";
          if (result) {
            this.codeReader.stopContinuousDecode();
            console.log("扫描结果", result);
           // alert(JSON.stringify(result));
            this.scanText = result.text;
            if (this.scanText) {
              this.tipShow = false;
              this.$store.dispatch("SET_SACNCODE", {code:result.text, type:this.type});
              let timer = setTimeout(() => {
                this.clickIndexLeft();
                clearTimeout(timer);
              }, 500);
            }
          }
          if (err && !err) {
            this.tipMsg = "识别失败";
            let timer = setTimeout(() => {
              this.tipShow = false;
              clearTimeout(timer);
            }, 2000);
            console.error(err);
          }
        }
      );
    },
    clickIndexLeft() {
      this.$router.back();
    },
  },
};
</script>
 
<style scoped>
.scan-index-bar {
  background-image: linear-gradient(-45deg, #42a5ff, #59cfff);
}
.van-nav-bar__title {
  color: #fff !important;
}
.scan-video {
  height: 80vh;
}
.scan-tip {
  width: 100vw;
  text-align: center;
  margin-bottom: 10vh;
  color: white;
  font-size: 5vw;
}
.page-scan {
  overflow-y: hidden;
  background-color: #363636;
}
</style>